package com.diligent.cloud.sfc.service.impl;

import com.alibaba.fastjson.JSON;
import com.canny.commons.model.Codes;
import com.canny.commons.model.ListResult;
import com.canny.commons.model.ObjectResult;
import com.canny.commons.model.Result;
import com.canny.commons.page.IPage;
import com.canny.commons.page.Pagination;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.diligent.cloud.identity.service.IdentityService;
import com.diligent.cloud.logistics.container.enums.BoxFillDocStatus;
import com.diligent.cloud.logistics.container.model.LcmBoxFill;
import com.diligent.cloud.logistics.container.model.LcmBoxFillDetail;
import com.diligent.cloud.logistics.container.model.LcmBoxFillMaster;
import com.diligent.cloud.logistics.container.model.LcmBoxLedger;
import com.diligent.cloud.logistics.container.service.LcmBoxFillFeignService;
import com.diligent.cloud.logistics.container.service.LcmBoxLedgerFeignService;
import com.diligent.cloud.primary.data.feign.service.mdm.MdmBaseFeignService;
import com.diligent.cloud.primary.data.feign.service.rt.RtMachineFeignService;
import com.diligent.cloud.primary.data.model.rt.RtMachine;
import com.diligent.cloud.primary.data.model.rt.RtWorkCenter;
import com.diligent.cloud.prodbatch.model.MfgProdBatch;
import com.diligent.cloud.prodbatch.model.MfgProdBatchResp;
import com.diligent.cloud.prodbatch.service.MfgProdBatchFeignService;
import com.diligent.cloud.sfc.config.OauthConfig;
import com.diligent.cloud.sfc.model.MfgConsume;
import com.diligent.cloud.sfc.model.StationType;
import com.diligent.cloud.sfc.model.detail.BoxDetailInfo;
import com.diligent.cloud.sfc.model.enums.Cwoc;
import com.diligent.cloud.sfc.model.enums.MatStatus;
import com.diligent.cloud.sfc.model.enums.StopReason;
import com.diligent.cloud.sfc.model.info.BoxInfo;
import com.diligent.cloud.sfc.model.info.ModelInfo;
import com.diligent.cloud.sfc.model.info.ProdBatchInfo;
import com.diligent.cloud.sfc.model.params.DevEnvironmentParams;
import com.diligent.cloud.sfc.model.params.WoOrderCompleteParams;
import com.diligent.cloud.sfc.service.*;
import com.diligent.cloud.sfc.util.ConverterUtil;
import com.diligent.cloud.web.model.PageAndCondition;
import com.diligent.cloud.workorder.enums.WoLotsStatus;
import com.diligent.cloud.workorder.model.WoLots;
import com.diligent.cloud.workorder.model.WoOperationCompleteDetail;
import com.diligent.cloud.workorder.model.WoOrder;
import com.diligent.cloud.workorder.service.WoLotsFeignService;
import com.diligent.cloud.workorder.service.WoOperationCompleteDetailFeignService;
import com.diligent.cloud.workorder.service.WoOrderFeignService;
import com.diligent.cloud.workordermd.feign.service.*;
import com.diligent.cloud.workordermd.model.*;
import com.diligent.foundation.data.model.v2.Condition;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.*;

/**
 * WorkshopSceneServiceImpl class
 *
 * @author xf107278
 * @date 3/30/2020
 */
@Service
public class WorkshopSceneServiceImpl implements WorkshopSceneService {

    private WoOrderFeignService orderFeignService;

    private MfgProdBatchFeignService mfgProdBatchFeignService;

    private IdentityService identityService;

    private MfgConsumeMasterFeignService mfgConsumeMasterFeignService;

    private MfgMdApplyUseFeignService mfgMdApplyUseFeignService;


    private MfgConsumeDetailFeignService mfgConsumeDetailFeignService;

    private MfgDevEnvironmentFeignService mfgDevEnvironmentFeignService;


    private MfgUserEnvironmentFeignService mfgUserEnvironmentFeignService;

    private MfgSfcMachStopFeignService mfgSfcMachStopFeignService;

    private ISfcService sfcService;

    private ProdBatchService prodBatchService;

    private final LcmBoxLedgerFeignService lcmBoxLedgerFeignService;

    private final WoOrderService sfcOrderService;


    private LcmBoxFillFeignService lcmBoxFillFeignService;

    private RtMachineFeignService rtMachineFeignService;

    private final WoLotsFeignService lotsFeignService;


    private final WoOperationCompleteDetailFeignService operationCompleteDetailFeignService;

    private final WorkShopExtrusionServiceImpl workShopExtrusionService;

    private final OauthConfig.RequestParams requestParams;
    private final MdmBaseFeignService mdmBaseFeignService;
    private final CraftDataService craftDataService;

    private final String TEME = "tech_event_mid_execption";

    @Value("${soa.url}")
    private String soaRequestUrl;

    public WorkshopSceneServiceImpl(WoOrderFeignService orderFeignService,
                                    MfgProdBatchFeignService mfgProdBatchFeignService,
                                    IdentityService identityService,
                                    MfgConsumeMasterFeignService mfgConsumeMasterFeignService,
                                    MfgMdApplyUseFeignService mfgMdApplyUseFeignService,
                                    MfgConsumeDetailFeignService mfgConsumeDetailFeignService,
                                    MfgDevEnvironmentFeignService mfgDevEnvironmentFeignService,
                                    MfgUserEnvironmentFeignService mfgUserEnvironmentFeignService,
                                    MfgSfcMachStopFeignService mfgSfcMachStopFeignService, ISfcService sfcService,
                                    ProdBatchService prodBatchService,
                                    LcmBoxLedgerFeignService lcmBoxLedgerFeignService,
                                    WoOrderService sfcOrderService,
                                    LcmBoxFillFeignService lcmBoxFillFeignService,
                                    RtMachineFeignService rtMachineFeignService, WoLotsFeignService lotsFeignService,
                                    WoOperationCompleteDetailFeignService operationCompleteDetailFeignService,
                                    WorkShopExtrusionServiceImpl workShopExtrusionService,
                                    OauthConfig.RequestParams requestParams, MdmBaseFeignService mdmBaseFeignService,
                                    CraftDataService craftDataService) {
        this.orderFeignService = orderFeignService;
        this.mfgProdBatchFeignService = mfgProdBatchFeignService;
        this.identityService = identityService;
        this.mfgConsumeMasterFeignService = mfgConsumeMasterFeignService;
        this.mfgMdApplyUseFeignService = mfgMdApplyUseFeignService;
        this.mfgConsumeDetailFeignService = mfgConsumeDetailFeignService;
        this.mfgDevEnvironmentFeignService = mfgDevEnvironmentFeignService;
        this.mfgUserEnvironmentFeignService = mfgUserEnvironmentFeignService;
        this.mfgSfcMachStopFeignService = mfgSfcMachStopFeignService;
        this.sfcService = sfcService;
        this.prodBatchService = prodBatchService;
        this.lcmBoxLedgerFeignService = lcmBoxLedgerFeignService;
        this.sfcOrderService = sfcOrderService;
        this.lcmBoxFillFeignService = lcmBoxFillFeignService;
        this.rtMachineFeignService = rtMachineFeignService;
        this.lotsFeignService = lotsFeignService;
        this.operationCompleteDetailFeignService = operationCompleteDetailFeignService;
        this.workShopExtrusionService = workShopExtrusionService;
        this.requestParams = requestParams;
        this.mdmBaseFeignService = mdmBaseFeignService;
        this.craftDataService = craftDataService;
    }


    @Override
    public ResponseEntity<Result> machStop(StopReason stopReason, String remark, String machCode, Principal principal) {

        MfgSfcMachStop mfgSfcMachStop = new MfgSfcMachStop();
        MfgUserEnvironment userEnvironmentByUserCode = sfcService.getUserEnvironmentByUserCode(principal.getName());
        Preconditions.checkNotNull(userEnvironmentByUserCode, "无法查询到令牌用户的身份信息");
        BeanUtils.copyProperties(userEnvironmentByUserCode, mfgSfcMachStop);

        mfgSfcMachStop.setStopReason(stopReason.getCode());
        mfgSfcMachStop.setStopReasonName(stopReason.getReason());
        mfgSfcMachStop.setIsClosed(0);
        mfgSfcMachStop.setIsCanceled(0);
        mfgSfcMachStop.setRemark(remark);
        mfgSfcMachStop.setMachCode(machCode);
        mfgSfcMachStop.setEnterCode(principal.getName());
        mfgSfcMachStop.setEnterName(principal.getName());
        mfgSfcMachStop.setEnterTime(new Date());
        mfgSfcMachStop.setModifyCode(null);
        mfgSfcMachStop.setModifyName(null);
        mfgSfcMachStop.setModifyTime(null);
        mfgSfcMachStop.setPostCode(principal.getName());
        mfgSfcMachStop.setPostName(principal.getName());
        mfgSfcMachStop.setPostTime(new Date());
        mfgSfcMachStop.setPeriodId(sfcService.getPeriodId());
        mfgSfcMachStop.setSystemId(requestParams.getSystemId());
        mfgSfcMachStop.setCompanyId(requestParams.getCompanyId());
        mfgSfcMachStop.setFormId(1L);

        PageAndCondition pageAndCondition = new PageAndCondition();
        Pagination pagination = new Pagination(1L, 1000000L);
        List<Condition> conditions = new ArrayList<>();
        conditions.add(new Condition("machCode", "eq", machCode, null));
        conditions.add(new Condition("endTime", "nn", 0, null));
        conditions.add(new Condition("systemId", "eq", userEnvironmentByUserCode.getSystemId(), null));
        pageAndCondition.setPagination(pagination);
        pageAndCondition.setConditions(conditions);
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<MfgProdBatch>>> search =
                mfgProdBatchFeignService.search(pageAndCondition);
        if (search.getBody() != null && search.getBody().getData() != null && search.getBody().getData().getRecords().size() != 0) {
            for (MfgProdBatch mfgProdBatch : search.getBody().getData().getRecords()) {
                mfgProdBatchFeignService.update(mfgProdBatch.getProdBatch(),
                        userEnvironmentByUserCode.getSystemId(), principal);
            }
        }
        conditions = new ArrayList<>();
        conditions.add(new Condition("machCode", "eq", machCode, null));
        conditions.add(new Condition("docStatus", "eq", "100", null));
        pageAndCondition.setConditions(conditions);
        pageAndCondition.setPagination(new Pagination(1L, 1L));
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<MfgMdApplyUse>>> mfgMdApplyUseResult =
                mfgMdApplyUseFeignService.selectDataByConditionPage(pageAndCondition);
        if (mfgMdApplyUseResult.getBody() != null && mfgMdApplyUseResult.getBody().getData() != null) {
            for (MfgMdApplyUse mfgMdApplyUse : mfgMdApplyUseResult.getBody().getData().getRecords()) {
                mfgMdApplyUse.setDocStatus(0);
                mfgMdApplyUse.setModifyTime(new Date());
                mfgMdApplyUse.setModifyName(principal.getName());
                mfgMdApplyUse.setModifyCode(principal.getName());
                mfgMdApplyUseFeignService.modify(mfgMdApplyUse);
            }
        }
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> insert =
                mfgSfcMachStopFeignService.insert(mfgSfcMachStop);

        ObjectResult result;
        if (insert.getBody() != null && insert.getBody().getData() != null) {
            result = new ObjectResult(insert.getBody().getData());

        } else {
            result = new ObjectResult();
            result.modifyCode(Codes.fail.getCode(), "新增模具停机失败");
        }
        return ResponseEntity.ok(result);
    }


    @Override
    public ResponseEntity<ObjectResult> updateMat(String matCode, String matName, String machCode,
                                                  Principal principal) {
        //根据机台寻找旧的生产批并结束掉
        MfgUserEnvironment userEnvironmentByUserCode = sfcService.getUserEnvironmentByUserCode(principal.getName());
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> prodBatchResult =
                mfgProdBatchFeignService.selectProdBatchByMatCode(userEnvironmentByUserCode.getMachCode(), matCode,
                        userEnvironmentByUserCode.getSystemId());
        if (prodBatchResult.getBody() != null && prodBatchResult.getBody().getData() != null) {
            MfgProdBatch mfgProdBatch = (MfgProdBatch) prodBatchResult.getBody().getData();
            if (mfgProdBatch.getEndTime() == null) {
                mfgProdBatchFeignService.update(mfgProdBatch.getProdBatch(), userEnvironmentByUserCode.getSystemId(),
                        principal);
            }
        }
        long periodId = sfcService.getPeriodId();

        MfgProdBatch prodBatch = new MfgProdBatch();
        prodBatch.setMatCode(matCode);
        prodBatch.setMatName(matName);
        prodBatch.setEnterName(principal.getName());
        prodBatch.setEnterCode(principal.getName());
        prodBatch.setEnterTime(new Date());
        prodBatch.setCompanyId(requestParams.getCompanyId());
        prodBatch.setSystemId(requestParams.getSystemId());
        prodBatch.setPeriodId(periodId);
        prodBatch.setMachCode(machCode);
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> add = mfgProdBatchFeignService.add(prodBatch);

        if (add.getBody() != null) {
            ObjectResult result = new ObjectResult(add.getBody().getData());
            result.modifyCode(add.getBody().getCode(), add.getBody().getMsg());
            return ResponseEntity.ok(result);
        }
        ObjectResult result = new ObjectResult();
        result.modifyCode(Codes.fail.getCode(), Codes.fail.getMsg());
        return ResponseEntity.ok(result);
    }

    //TODO 基础信息表中查询
    @Override
    public ResponseEntity<Result> modifyMdStatus(String matCode, Principal principal) {
        MfgUserEnvironment userEnvironment = sfcService.getUserEnvironmentByUserCode(principal.getName());

        PageAndCondition pageAndCondition = new PageAndCondition();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(new Condition("docStatus", "eq", MatStatus.start.getStatus(), null));
        conditions.add(new Condition("matCode", "eq", matCode, null));
        conditions.add(new Condition("machCode", "eq", userEnvironment.getMachCode(), null));

        pageAndCondition.setConditions(conditions);
        pageAndCondition.setPagination(new Pagination(1L, 1L));
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<MfgMdApplyUse>>> mfgMdApplyUseResult =
                mfgMdApplyUseFeignService.selectDataByConditionPage(pageAndCondition);

        ObjectResult result;
        if (mfgMdApplyUseResult.getBody() != null && mfgMdApplyUseResult.getBody().getData().getRecords().size() != 0) {
            MfgMdApplyUse mfgMdApplyUse =
                    mfgMdApplyUseResult.getBody().getData().getRecords().stream().findFirst().get();
            mfgMdApplyUse.setDocStatus(MatStatus.processing.getStatus());
            mfgMdApplyUse.setModifyCode(principal.getName());
            mfgMdApplyUse.setModifyName(principal.getName());
            mfgMdApplyUse.setModifyTime(new Date());

            ResponseEntity<com.diligent.cloud.primary.data.model.Result> modify =
                    mfgMdApplyUseFeignService.modify(mfgMdApplyUse);
            result = ConverterUtil.ConverterByResult(modify.getBody());
        } else {
            result = new ObjectResult(null);
            result.setCode(Codes.fail.getCode());
            result.setMsg(Strings.lenientFormat("当前[%s]机台查询不到此[%s]模具", userEnvironment.getMachCode(), matCode));
        }
        return ResponseEntity.ok(result);
    }


    @Override
    public ResponseEntity<Result> modifyAsStatus(Long asId, Principal principal) {
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<MfgConsumeMaster>> consumeMasterResult =
                mfgConsumeMasterFeignService.getById(asId.toString());
        Preconditions.checkNotNull(consumeMasterResult.getBody(), "物料消耗表中查询不到此[%s]ID", asId);

        MfgConsumeMaster consumeMaster = consumeMasterResult.getBody().getData();
        consumeMaster.setDocStatus(50);
        consumeMaster.setModifyCode(principal.getName());
        consumeMaster.setModifyName(principal.getName());
        consumeMaster.setModifyTime(new Date());

        return ResponseEntity.ok(ConverterUtil.ConverterByResult(mfgConsumeMasterFeignService.modify(consumeMaster).getBody()));
    }


    @Override
    public ResponseEntity<Result> insertMfgMachEven(Principal principal) {
        return null;
    }

    @Override
    @LcnTransaction
    @Transactional
    public ResponseEntity<Result> updateMould(Long mdId, Long orderId, String accessToken, String previousModelId,
                                              Principal principal) throws Exception {
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<MfgMdApplyUse>> mfgMdApplyUseRequest =
                mfgMdApplyUseFeignService.getById(String.valueOf(mdId));
        Preconditions.checkNotNull(mfgMdApplyUseRequest.getBody(), "查询不到此模具");
        MfgMdApplyUse mfgMdApplyUse = mfgMdApplyUseRequest.getBody().getData();

        if (mfgMdApplyUse.getDocStatus().intValue() == MatStatus.start.getStatus().intValue()) {
            ObjectResult<String> result = new ObjectResult<>(mfgMdApplyUse.getMatCode());
            result.modifyCode(Codes.fail.getCode(), "此模具并非在加温状态");
            return ResponseEntity.ok(result);
        }

        ResponseEntity<com.diligent.cloud.primary.data.model.Result> woOrderResponse =
                orderFeignService.selectById(orderId);
        Preconditions.checkNotNull(woOrderResponse.getBody(), "查询不到此工单");
        WoOrder woOrder = (WoOrder) woOrderResponse.getBody().getData();

        // 修改斯欧模具型号时，触发斯欧异常则直接退出
/*        ObjectResult result = craftDataService.setMouldId(mfgMdApplyUse.getMatCode(), woOrder.getWoOrder());
        if (result.getCode() == 1) {
            ResponseEntity<ListResult> elineEventTableResult =
                    craftDataService.getElineEventTable(woOrder.getMachineCode()
                            , String.valueOf(System.currentTimeMillis() / 1000), "5");
            for (LinkedHashMap map : (List<LinkedHashMap>) elineEventTableResult.getBody().getData()) {
            //切换大小写
                map = replaceFirstByMap(map);
                ElineEventTable elineEventTable = new ElineEventTable();
                org.apache.commons.beanutils.BeanUtils.populate(elineEventTable, map);
                if (TEME.equalsIgnoreCase(elineEventTable.getEvent())) {
                    result = new ObjectResult<String>(null);
                    result.modifyCode(Codes.fail.getCode(), "换模异常");
                    return ResponseEntity.ok(result);
                }
            }
        }*/

        //查询此机台最后一个未结束的生产批 停止掉
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<MfgProdBatch>> prodBatchResult =
                mfgProdBatchFeignService.getByBatchLast(woOrder.getMachineCode(), woOrder.getSystemId());
        if (prodBatchResult.getBody() != null && prodBatchResult.getBody().getData() != null & previousModelId != null) {
            MfgProdBatch prodBatch = prodBatchResult.getBody().getData();

            mfgProdBatchFeignService.update(prodBatch.getProdBatch(), prodBatch.getSystemId(), principal);
        } else if (prodBatchResult.getBody() != null && prodBatchResult.getBody().getData() != null & previousModelId == null) {
            ObjectResult<String> result = new ObjectResult<String>(mfgMdApplyUse.getMatCode());
            result.modifyCode(Codes.fail.getCode(), "有上一个未结束生产批需要提供上一个模具号");
            return ResponseEntity.ok(result);
        }

        //修改模具状态
        mfgMdApplyUse.setModifyName(principal.getName());
        mfgMdApplyUse.setModifyCode(principal.getName());
        mfgMdApplyUse.setModifyTime(new Date());
        mfgMdApplyUse.setDocStatus(MatStatus.end.getStatus());


        //新增批次
        MfgProdBatch mfgProdBatch = new MfgProdBatch();
        BeanCopier beanCopier = BeanCopier.create(MfgMdApplyUse.class, MfgProdBatch.class, false);
        mfgProdBatch.setMachCode(woOrder.getMachineCode());
        beanCopier.copy(mfgMdApplyUse, mfgProdBatch, null);
        mfgProdBatch.setEnterCode(principal.getName());
        mfgProdBatch.setEnterName(principal.getName());
        mfgProdBatch.setEnterTime(new Date());
        mfgProdBatch.setModifyCode(null);
        mfgProdBatch.setModifyName(null);
        mfgProdBatch.setModifyTime(null);
        mfgProdBatch.setId(null);
        mfgProdBatch.setCv4(mfgMdApplyUse.getMatCode());
        mfgProdBatch.setMatName(woOrder.getMatName());
        mfgProdBatch.setMatCode(mfgMdApplyUse.getMatCodeCv());
        mfgProdBatch.setFormId(woOrder.getFormId());
        mfgProdBatch.setSystemId(requestParams.getCompanyId());
        mfgProdBatch.setCompanyId(requestParams.getCompanyId());
        mfgProdBatch.setPeriodId(sfcService.getPeriodId());


        ResponseEntity<com.diligent.cloud.primary.data.model.Result> mfgProdBatchResponseEntity =
                mfgProdBatchFeignService.add(mfgProdBatch);

        String prodBatch = "";
        if (mfgProdBatchResponseEntity.getBody() != null && mfgProdBatchResponseEntity.getBody().getData() != null) {
            MfgProdBatchResp mfgProdBatchResp = (MfgProdBatchResp) mfgProdBatchResponseEntity.getBody().getData();
            if (mfgProdBatchResp != null) {
                prodBatch = mfgProdBatchResp.getProdBatch();
            }
        }

        Boolean previousModel = previousModelId == null ? false : !"null".equalsIgnoreCase(previousModelId) ? true :
                false;
        if (previousModel) {
            ResponseEntity<com.diligent.cloud.primary.data.model.Result<MfgMdApplyUse>> mdApplyUseResult =
                    mfgMdApplyUseFeignService.getById(previousModelId);
            if (mdApplyUseResult.getBody() != null && mdApplyUseResult.getBody().getData() != null) {
                MfgMdApplyUse previousMd = mdApplyUseResult.getBody().getData();
                previousMd.setDocStatus(0);
                previousMd.setModifyTime(new Date());
                previousMd.setModifyName(principal.getName());
                previousMd.setModifyCode(principal.getName());
                mfgMdApplyUseFeignService.modify(previousMd);
            }
        }
        //修改限制模具状态
        mfgMdApplyUseFeignService.modify(mfgMdApplyUse);

        //查询工单是否有工序完工信息
        PageAndCondition pageAndCondition = new PageAndCondition();
        pageAndCondition.setPagination(new Pagination(1L, 1L));
        List<Condition> conditions = new ArrayList<>();
        conditions.add(new Condition("woOrder", "eq", woOrder.getWoOrder(), null));
        pageAndCondition.setConditions(conditions);
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoOperationCompleteDetail>>> operationCompleteDetailPage =
                operationCompleteDetailFeignService.page(pageAndCondition);

        //没有完工信息则新增
        if (operationCompleteDetailPage.getBody() != null && operationCompleteDetailPage.getBody().getData().getRecords().size() == 0) {
            sfcService.addOperationComplete(woOrder, prodBatch,
                    null, false, principal);
        } else if (operationCompleteDetailPage.getBody() != null && operationCompleteDetailPage.getBody().getData().getRecords().size() != 0) {
            //有工序完工单则更新工序批次
            WoOperationCompleteDetail operationCompleteDetail =
                    operationCompleteDetailPage.getBody().getData().getRecords().stream().findFirst().get();
            operationCompleteDetail.setProdBatch(prodBatch);
            operationCompleteDetail.setModifyTime(new Date());
            operationCompleteDetail.setModifyCode(principal.getName());
            operationCompleteDetail.setModifyName(principal.getName());
            operationCompleteDetailFeignService.update(operationCompleteDetail);
        }

        return ResponseEntity.ok(new ObjectResult<>(prodBatch));
    }


    @Override
    @Transactional
    @LcnTransaction
    public ResponseEntity<Result> updateAluminumStick(Long asId, Long mdId, Long orderId, Principal principal) {

        ResponseEntity<com.diligent.cloud.primary.data.model.Result<MfgConsumeMaster>> mfgConsumeMasterResultEntity =
                mfgConsumeMasterFeignService.getById(String.valueOf(asId));
        Preconditions.checkNotNull(mfgConsumeMasterResultEntity.getBody(), "查询不到此铝棒");

        ResponseEntity<com.diligent.cloud.primary.data.model.Result> orderResponseEntity =
                orderFeignService.selectById(orderId);
        Preconditions.checkNotNull(orderResponseEntity.getBody(), "查询不到此工单");

        ResponseEntity<com.diligent.cloud.primary.data.model.Result<MfgMdApplyUse>> mfgMdApplyUseResponseEntity =
                mfgMdApplyUseFeignService.getById(String.valueOf(mdId));
        Preconditions.checkNotNull(mfgMdApplyUseResponseEntity.getBody(), "查询不到此模具");
        WoOrder order = (WoOrder) orderResponseEntity.getBody().getData();

        MfgConsumeMaster mfgConsumeMaster = mfgConsumeMasterResultEntity.getBody().getData();

        MfgMdApplyUse mfgMdApplyUse = mfgMdApplyUseResponseEntity.getBody().getData();

        if (mfgMdApplyUse.getDocStatus().intValue() != MatStatus.end.getStatus()) {
            ObjectResult<Long> result = new ObjectResult<>(mfgMdApplyUse.getId());
            result.modifyCode(Codes.fail.getCode(), "所需模具非加温状态");
            return ResponseEntity.ok(result);
        }
        //更改状态
        mfgConsumeMaster.setModifyTime(new Date());
        mfgConsumeMaster.setEnterTime(new Date());
        mfgConsumeMaster.setModifyName(principal.getName());
        mfgConsumeMaster.setModifyCode(principal.getName());
        mfgConsumeMaster.setEnterCode(principal.getName());
        mfgConsumeMaster.setEnterName(principal.getName());
        mfgConsumeMaster.setDocStatus(MatStatus.end.getStatus());


        //查询到最后一个批次
        ObjectResult<MfgConsumeMaster> result;
        ResponseEntity<ObjectResult> lastOneBatch = prodBatchService.getLastOneBatch(order.getMachineCode(),
                order.getSystemId(), principal);
        Preconditions.checkNotNull(lastOneBatch.getBody(), "查询不到批次");
        ProdBatchInfo prodBatchInfo = (ProdBatchInfo) lastOneBatch.getBody().getData();
        mfgConsumeMaster.setProdBatch(prodBatchInfo.getProdBatch());

        ResponseEntity<com.diligent.cloud.primary.data.model.Result> mfgConsumeMasterModify =
                mfgConsumeMasterFeignService.modify(mfgConsumeMaster);

        Preconditions.checkNotNull(mfgConsumeMasterModify.getBody(), "修改铝棒状态失败");
        mfgConsumeMaster = (MfgConsumeMaster) mfgConsumeMasterModify.getBody().getData();


        //更改消耗信息
        Condition condition = new Condition("masterId", "eq", mfgConsumeMaster.getId(), null);
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> mfgConsumeDetailResponseEntity =
                mfgConsumeDetailFeignService.selectDataByCondition(Collections.singletonList(condition));

        Preconditions.checkNotNull(mfgConsumeDetailResponseEntity.getBody(), "修改铝棒状态失败");

        List<LinkedHashMap> mfgConsumeDetails =
                (List<LinkedHashMap>) mfgConsumeDetailResponseEntity.getBody().getData();
        MfgConsumeDetail consumeDetail =
                JSON.parseObject(JSON.toJSONString(mfgConsumeDetails.stream().findFirst().get()),
                        MfgConsumeDetail.class);

        consumeDetail.setModifyCode(principal.getName());
        consumeDetail.setModifyName(principal.getName());
        consumeDetail.setModifyTime(new Date());
        consumeDetail.setRefCode(order.getWoOrder());
        consumeDetail.setRefRowId(String.valueOf(order.getId()));
        mfgConsumeDetailFeignService.modify(consumeDetail);
        mfgConsumeMaster.setLotCode(consumeDetail.getLotCode());

        result = new ObjectResult<>(mfgConsumeMaster);
        result.modifyCode(Codes.success.getCode(), "!更换成功");

        PageAndCondition pageAndCondition = new PageAndCondition();
        pageAndCondition.setPagination(new Pagination(1L, 1L));
        List<Condition> conditions = new ArrayList<>();
        conditions.add(new Condition("prodBatch", "eq", mfgConsumeMaster.getProdBatch(), null));
        conditions.add(new Condition("woOrder", "eq", order.getWoOrder(), null));
        pageAndCondition.setConditions(conditions);
        //找到此工序完工单并添加消耗主表id进去
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoOperationCompleteDetail>>> operationCompleteDetailPage =
                operationCompleteDetailFeignService.page(pageAndCondition);
        Preconditions.checkNotNull(operationCompleteDetailPage.getBody(), "查询不到工序完工单");
        if (operationCompleteDetailPage.getBody().getData().getRecords().size() != 0) {
            WoOperationCompleteDetail operationCompleteDetail =
                    operationCompleteDetailPage.getBody().getData().getRecords().stream().findFirst().get();
            operationCompleteDetail.setUsrTxt1(asId.toString());
            operationCompleteDetailFeignService.update(operationCompleteDetail);
        }


        return ResponseEntity.ok(result);
    }

    @Override
    public ResponseEntity<Result> getEquipmentMaintenance(Principal principal) {
        return null;
    }

    @Override
    public ResponseEntity<Result> getDevEnvironmentInfo(String devMac, Principal principal) {
        Condition condition = new Condition("devMac", "eq", devMac, null);
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> devEnvironmentResponse =
                mfgDevEnvironmentFeignService.selectDataByCondition(Collections.singletonList(condition));
        Preconditions.checkNotNull(devEnvironmentResponse.getBody(), "查询不到设备信息");
        if (devEnvironmentResponse.getBody().getCode() == 0) {
            List<LinkedHashMap> devEnvironments = (List<LinkedHashMap>) devEnvironmentResponse.getBody().getData();
            MfgDevEnvironment mfgDevEnvironment =
                    JSON.parseObject(JSON.toJSONString(devEnvironments.stream().findFirst().get()),
                            MfgDevEnvironment.class);
            MfgUserEnvironment userEnvironmentByUserCode = sfcService.getUserEnvironmentByUserCode(principal.getName());
            Preconditions.checkNotNull(mfgDevEnvironment, "找不到令牌的用户信息");
            mfgDevEnvironment.setRemark(userEnvironmentByUserCode.getCwocCode());
            return ResponseEntity.ok(ConverterUtil.ConverterByData(mfgDevEnvironment, Codes.success.getCode(),
                    Codes.success.getMsg()));
        } else {
            return ResponseEntity.ok(ConverterUtil.ConverterByData(null, Codes.fail.getCode(), "没有此机台信息"));
        }

    }


    @Override
    public ResponseEntity<Result> addMatMd(Principal principal) {
        return null;
    }

    @Override
    public ResponseEntity<Result> addMatAa(Principal principal) {
        return null;
    }

    @Override
    public ResponseEntity<Result> getWarmingStatusAaList(String machCode, String material, String systemId) {
        List<Condition> conditions = getMatParameterList(machCode, material, systemId);
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> mfgConsumeMasterRequest =
                mfgConsumeMasterFeignService.selectDataByCondition(conditions);
        ArrayList<MfgConsume> answer = new ArrayList<>();
        if (mfgConsumeMasterRequest.getBody() != null && mfgConsumeMasterRequest.getBody().getCode() == 0) {
            List<LinkedHashMap> mfgConsumeMasters = (List<LinkedHashMap>) mfgConsumeMasterRequest.getBody().getData();
            for (int j = 0; j < mfgConsumeMasters.size(); j++) {
                MfgConsumeMaster mfgConsumeMaster = JSON.parseObject(JSON.toJSONString(mfgConsumeMasters.get(j)),
                        MfgConsumeMaster.class);

                conditions = new ArrayList<>();

                Condition masterIdCondition = new Condition("masterId", "eq", mfgConsumeMaster.getId(), null);
                conditions.add(masterIdCondition);

                ResponseEntity<com.diligent.cloud.primary.data.model.Result> mfgConsumeDetailRequest =
                        mfgConsumeDetailFeignService.selectDataByCondition(conditions);
                Preconditions.checkNotNull(mfgConsumeDetailRequest.getBody(), "查询不到此[%s]消耗主表的细节信息",
                        mfgConsumeMaster.getId());
                List<LinkedHashMap> mfgConsumeDetails =
                        (List<LinkedHashMap>) mfgConsumeDetailRequest.getBody().getData();

                MfgConsumeDetail mfgConsumeDetail =
                        JSON.parseObject(JSON.toJSONString(mfgConsumeDetails.stream().findFirst().get()),
                                MfgConsumeDetail.class);
                MfgConsume mfgConsume = new MfgConsume();
                mfgConsume.setMfgConsumeMaster(mfgConsumeMaster);
                mfgConsume.setMfgConsumeDetail(mfgConsumeDetail);

                answer.add(mfgConsume);
            }
        }
        if (answer.size() != 0) {
            return ResponseEntity.ok(ConverterUtil.ConverterByData(answer, Codes.success.getCode(), "查询成功"));

        } else {
            return ResponseEntity.ok(ConverterUtil.ConverterByData(answer, Codes.success.getCode(), "铝棒列表为空"));
        }
    }

    @Override
    public ResponseEntity<Result> getWarmingStatusMdList(String machCode, String matCodeCv, String systemId) {
        ResponseEntity<ListResult<MfgMdApplyUse>> responseEntity = null;
        if ("All".equalsIgnoreCase(matCodeCv)) {
            responseEntity =
                    mfgMdApplyUseFeignService.getWarmingStateMdList(null, machCode);
        } else {
            responseEntity =
                    mfgMdApplyUseFeignService.getWarmingStateMdList(matCodeCv, machCode);
        }

        ArrayList<ModelInfo> answer = new ArrayList<>();
        if (responseEntity.getBody() != null && responseEntity.getBody().getCode() == 0) {
            List<MfgMdApplyUse> mdApplyUses = responseEntity.getBody().getData();
            Iterator<MfgMdApplyUse> iterator = mdApplyUses.iterator();
            while (iterator.hasNext()) {
                MfgMdApplyUse mfgMdApplyUse = iterator.next();
                ModelInfo modelInfo = new ModelInfo();
                BeanUtils.copyProperties(mfgMdApplyUse, modelInfo);
                answer.add(modelInfo);
            }
            return ResponseEntity.ok(ConverterUtil.ConverterByData(answer, Codes.success.getCode(), "查询成功"));

        } else {
            return ResponseEntity.ok(ConverterUtil.ConverterByData(answer, Codes.success.getCode(), "模具列表为空"));
        }
    }


    @Override
    public ResponseEntity<Result> moldRelease(Long mdId, Principal principal) {
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<MfgMdApplyUse>> byId =
                mfgMdApplyUseFeignService.getById(String.valueOf(mdId));
        Preconditions.checkNotNull(byId.getBody(), "查询不到此模具");
        MfgMdApplyUse mfgMdApplyUse = byId.getBody().getData();
        mfgMdApplyUse.setDocStatus(0);
        mfgMdApplyUse.setModifyCode(principal.getName());
        mfgMdApplyUse.setModifyName(principal.getName());
        mfgMdApplyUse.setModifyTime(new Date());

        //停批次
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<MfgProdBatch>> prodBatchResult =
                mfgProdBatchFeignService.getByBatchLast(mfgMdApplyUse.getMachCode(), mfgMdApplyUse.getSystemId());
        if (prodBatchResult.getBody() != null && prodBatchResult.getBody().getData() != null) {
            MfgProdBatch prodBatch = prodBatchResult.getBody().getData();

            mfgProdBatchFeignService.update(prodBatch.getProdBatch(), prodBatch.getSystemId(), principal);
        }

        ResponseEntity<com.diligent.cloud.primary.data.model.Result> modify =
                mfgMdApplyUseFeignService.modify(mfgMdApplyUse);
        return ResponseEntity.ok(ConverterUtil.ConverterByResult(modify.getBody()));
    }


    @Override
    @LcnTransaction
    @Transactional
    public ResponseEntity<Result> inbox(WoOrderCompleteParams orderCompleteParams, Principal principal) {
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> orderResult =
                orderFeignService.selectById(orderCompleteParams.getOrderId());
        Preconditions.checkNotNull(orderResult.getBody(), "查询不到此工单");
        WoOrder order = (WoOrder) orderResult.getBody().getData();

        WoOperationCompleteDetail operationCompleteDetailByWoOrder =
                sfcService.getOperationCompleteDetailByWoOrder(order.getWoOrder());
        Preconditions.checkNotNull(operationCompleteDetailByWoOrder, "查询不到此工单的工序完工信息");

        ListResult result = workShopExtrusionService.boxReportedFilter(null, order.getId().toString(), true);
        int totalDigit = 0;
        if (result.getData().size() != 0) {
            List<BoxInfo> boxInfos = result.getData();
            for (BoxInfo boxInfo : boxInfos) {
                totalDigit += boxInfo.getDigit().intValue();
            }
        }
        ObjectResult objectResult;
        if (operationCompleteDetailByWoOrder.getDigit().longValue() < (orderCompleteParams.getDigit().intValue() + totalDigit)) {
            objectResult = new ObjectResult(null);
            objectResult.setCode(Codes.fail.getCode());
            objectResult.setMsg("此工单%s数量已超过剪切完工数量");
        } else {
            objectResult = addBoxFillByOrderComplete(orderCompleteParams, principal);
            Preconditions.checkNotNull(result, "装框失败");
        }

        return ResponseEntity.ok(objectResult);
    }

    @Override
    public ResponseEntity<Result> inboxDetail(Long orderId, String prodBatch, String machCode, Long systemId) {
        BoxDetailInfo boxDetailInfo = new BoxDetailInfo();

        //未完工
        ResponseEntity<ListResult> sameOrderByProdBatch = sfcOrderService.getSameOrderByProdBatch(prodBatch,
                machCode,
                systemId, StationType.挤压工位, 0, 1);
        if (sameOrderByProdBatch.getBody() != null && sameOrderByProdBatch.getBody().getData() != null) {
            List<LinkedHashMap> orders = (List<LinkedHashMap>) sameOrderByProdBatch.getBody().getData();
            boxDetailInfo.setSameBatchWaitOrder(orders.size());

            Long waitTotalPcs = 0L;
            for (LinkedHashMap orderMap : orders) {
                WoOrder order = JSON.parseObject(JSON.toJSONString(orderMap),
                        WoOrder.class);
                waitTotalPcs = waitTotalPcs + order.getDeliveryDigit().longValue();
            }
            boxDetailInfo.setWaitTotalPcs(waitTotalPcs);
            IPage<LcmBoxLedger> idleBox = sfcService.getIdleBox(Cwoc.挤压车间.getCwocCode(), 1L, 1000L);
            if (idleBox != null) {
                boxDetailInfo.setAvailableBox(idleBox.getTotal().intValue());

            } else {
                boxDetailInfo.setAvailableBox(0);
            }

            ResponseEntity<com.diligent.cloud.primary.data.model.Result> orderResult =
                    orderFeignService.selectById(orderId);
            Preconditions.checkNotNull(orderResult.getBody(), "查询不到Id为[%s]的工单", orderId);
            WoOrder order = (WoOrder) orderResult.getBody().getData();
            boxDetailInfo.setCompleteDigit(order.getDeliveryDigit().longValue());
            boxDetailInfo.setRequireDigit(order.getDeliveryDigit().longValue());
        }
        //已完工
        sameOrderByProdBatch = sfcOrderService.getSameOrderByProdBatch(prodBatch, machCode,
                systemId, StationType.剪切工位, 1, 1);

        if (sameOrderByProdBatch.getBody()!=null && sameOrderByProdBatch.getBody().getData() != null) {
            List<LinkedHashMap> orders = (List<LinkedHashMap>) sameOrderByProdBatch.getBody().getData();

            Long inBoxTotalPcs = 0L;
            for (LinkedHashMap orderMap : orders) {
                WoOrder woOrder = JSON.parseObject(JSON.toJSONString(orderMap),
                        WoOrder.class);
                inBoxTotalPcs = inBoxTotalPcs + woOrder.getDeliveryDigit().longValue();
            }
            boxDetailInfo.setInBoxTotalPcs(inBoxTotalPcs.intValue());
        }

        return ResponseEntity.ok(new ObjectResult<>(boxDetailInfo));
    }

    @Override
    public ResponseEntity<Result> getDevInfo(Boolean login, Principal principal) {

        MfgUserEnvironment mfgUserEnvironment = sfcService.getUserEnvironmentByUserCode(principal.getName());
        Preconditions.checkNotNull(mfgUserEnvironment, "查询不到此[%S]用户", principal.getName());
        if (login) {
            return ResponseEntity.ok(new ObjectResult<>(mfgUserEnvironment));
        }

        PageAndCondition pageAndCondition = new PageAndCondition();
        pageAndCondition.setPagination(new Pagination(1L, 1000000L));
        pageAndCondition.setConditions(Collections.singletonList(new Condition("machCode", "eq",
                mfgUserEnvironment.getMachCode(), null)));



        DevEnvironmentParams devEnvironmentParams = new DevEnvironmentParams();
        //TODO 待查询方法
        devEnvironmentParams.setDepartmentCode("00010113");
        devEnvironmentParams.setDepartmentName("数字应用2部");
        devEnvironmentParams.setWorkCenterCode(mfgUserEnvironment.getCwocCode());
        devEnvironmentParams.setWorkCenterName(mfgUserEnvironment.getCwocName());
        devEnvironmentParams.setUserCode(mfgUserEnvironment.getUserCode());
        devEnvironmentParams.setUserName(mfgUserEnvironment.getUserName());

        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<RtMachine>>> rtMachinePage =
                rtMachineFeignService.selectDataByConditionPage(pageAndCondition);
        Preconditions.checkNotNull(rtMachinePage.getBody(),"查询不到车间信息");
        devEnvironmentParams.setMachine(rtMachinePage.getBody().getData().getRecords().stream().findFirst().get());


        pageAndCondition.setConditions(new ArrayList<>());
        rtMachinePage = rtMachineFeignService.selectDataByConditionPage(pageAndCondition);
        if (rtMachinePage.getBody()!=null && rtMachinePage.getBody().getData()!=null){
            devEnvironmentParams.setMachines(rtMachinePage.getBody().getData().getRecords());
        }


        return ResponseEntity.ok(new ObjectResult<>(devEnvironmentParams));
    }

    @Override
    public ResponseEntity<Result> modifyDev(Long machId, Principal principal) {
        MfgUserEnvironment mfgUserEnvironment = sfcService.getUserEnvironmentByUserCode(principal.getName());
        Preconditions.checkNotNull(mfgUserEnvironment, "查询不到此[%S]用户", principal.getName());
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<RtMachine>> rtMachineResult =
                rtMachineFeignService.getById(machId.toString());
        Preconditions.checkNotNull(rtMachineResult.getBody(),"查询不到此车间信息");
        if (rtMachineResult.getBody().getCode() == 0) {
            RtMachine machine = rtMachineResult.getBody().getData();
            mfgUserEnvironment.setMachCode(machine.getMachCode());
            mfgUserEnvironment.setMachName(machine.getMachName());
            return ResponseEntity.ok(ConverterUtil.ConverterByResult(mfgUserEnvironmentFeignService.modify(mfgUserEnvironment).getBody()));
        }
        ObjectResult<Object> result = new ObjectResult<>();
        result.modifyCode(Codes.fail.getCode(), Codes.fail.getMsg());
        return ResponseEntity.ok(result);
    }

    @Override
    public ResponseEntity<Result> getDevInfo(String machName) {
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> rtMachineResult =
                rtMachineFeignService.selectDataByCondition(Collections.singletonList(new Condition("machCode",
                        "likeb", machName, null)));

        ListResult result ;
        if (rtMachineResult.getBody()!=null && rtMachineResult.getBody().getData()!=null && rtMachineResult.getBody().getCode() != 100) {

            result = new ListResult((List) rtMachineResult.getBody().getData());
            result.modifyCode(rtMachineResult.getBody().getCode(), rtMachineResult.getBody().getMsg());
        } else {
            result = new ListResult(new ArrayList());
            result.modifyCode(Codes.success.getCode(), "查询不到机台");
        }

        return ResponseEntity.ok(result);
    }


    private List<Condition> getMatParameterList(String machCode,
                                                String material, String systemId) {
        List<Condition> conditions = new ArrayList<>();
        Condition machCodeCondition = new Condition("machCode", "eq", machCode, null);
        Condition systemIdCondition = new Condition("systemId", "eq", systemId, null);
        if (material != null) {
            if (!"All".equalsIgnoreCase(material)) {
                Condition matTypeCondition = new Condition("matType", "eq", material, null);
                conditions.add(matTypeCondition);
            }
            Condition docStatusCondition = new Condition("docStatus", "in",
                    MatStatus.processing.getStatus() + "," + MatStatus.end.getStatus(), null);
            conditions.add(docStatusCondition);
        }
        conditions.add(machCodeCondition);
        conditions.add(systemIdCondition);

        return conditions;
    }

    private ObjectResult addBoxFillByOrderComplete(WoOrderCompleteParams orderCompleteParams, Principal principal) {
        LcmBoxFill lcmBoxFill = new LcmBoxFill();
        LcmBoxFillMaster lcmBoxFillMaster = new LcmBoxFillMaster();
        LcmBoxFillDetail lcmBoxFillDetail = new LcmBoxFillDetail();
        //查询工单
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> orderFeignResult =
                orderFeignService.selectById(orderCompleteParams.getOrderId());
        Preconditions.checkNotNull(orderFeignResult.getBody(), "工单为空");
        //查询物流容器
        ResponseEntity<com.diligent.cloud.primary.data.model.Result> boxLedgerResult =
                lcmBoxLedgerFeignService.getBoxLedger(orderCompleteParams.getBoxId());
        Preconditions.checkNotNull(boxLedgerResult.getBody(), "不存在此框");
        LcmBoxLedger boxLedger = (LcmBoxLedger) boxLedgerResult.getBody().getData();

        WoOrder order = (WoOrder) orderFeignResult.getBody().getData();
        RtWorkCenter workCenter = sfcService.getWorkCenterByCwocCode(order.getWorkCenterCode());
        RtMachine machineInfo = sfcService.getMachineByMachCode(orderCompleteParams.getMachineCode());

        long periodId = sfcService.getPeriodId();


        BeanUtils.copyProperties(order, lcmBoxFillMaster);
        lcmBoxFillMaster.setId(identityService.getIdentity());
//        lcmBoxFillMaster.setDocCode(iBusinessNumberControllerFeign.nextId(order.getSystemId(),
//                order.getFormId(), "boxFill", "lcm", new HashMap<>()).getBody());
//        lcmBoxFillMaster.setDocDate(LocalDate.now());
        lcmBoxFillMaster.setDocType(BoxFillDocStatus.INSERT.getStatus());
        lcmBoxFillMaster.setBoxId(orderCompleteParams.getBoxId());
        lcmBoxFillMaster.setBoxCode(boxLedger.getCode());
        lcmBoxFillMaster.setCompanyCode(machineInfo.getCompanyCode());
        lcmBoxFillMaster.setCompanyName(machineInfo.getCompanyName());
        //lcmBoxFillMaster.setStorageId(workCenter.get);
        lcmBoxFillMaster.setStorageCode(workCenter.getStorageCode());
        lcmBoxFillMaster.setStorageName(workCenter.getStorageName());
        lcmBoxFillMaster.setCwocCode(workCenter.getCwocCode());
        lcmBoxFillMaster.setCwocName(workCenter.getCwocName());
        lcmBoxFillMaster.setEnterName(principal.getName());
        lcmBoxFillMaster.setEnterCode(principal.getName());
        lcmBoxFillMaster.setEnterTime(new Date());
        lcmBoxFillMaster.setPeriodId(periodId);
        lcmBoxFillMaster.setSystemId(requestParams.getSystemId());
        lcmBoxFillMaster.setCompanyId(requestParams.getCompanyId());
        lcmBoxFillMaster.setFormId(1L);

        lcmBoxFillDetail.setMasterId(lcmBoxFillMaster.getId());
        lcmBoxFillDetail.setDocCode(lcmBoxFillMaster.getDocCode());
        lcmBoxFillDetail.setMatCode(order.getMatCode());
        lcmBoxFillDetail.setMatName(order.getMatName());
        lcmBoxFillDetail.setDigit(orderCompleteParams.getDigit());
        lcmBoxFillDetail.setEnterName(principal.getName());
        lcmBoxFillDetail.setEnterCode(principal.getName());
        lcmBoxFillDetail.setEnterTime(new Date());
        lcmBoxFillDetail.setRefBoxCode(boxLedger.getCode());
        lcmBoxFillDetail.setRefWoOrder(order.getId().toString());
        lcmBoxFillDetail.setTheoryWeight(new BigDecimal(0));
        lcmBoxFillDetail.setSystemId(requestParams.getSystemId());
        lcmBoxFillDetail.setCompanyId(requestParams.getCompanyId());
        lcmBoxFillDetail.setBatchCode(order.getBatchCode());
        lcmBoxFillDetail.setPeriodId(periodId);


        lcmBoxFill.setLcmBoxFillMaster(lcmBoxFillMaster);
        lcmBoxFill.setLcmBoxFillDetail(lcmBoxFillDetail);

        ResponseEntity<com.diligent.cloud.primary.data.model.Result> boxFillResult =
                lcmBoxFillFeignService.handingMaterial(lcmBoxFill);

        if (boxFillResult.getBody()!=null && boxFillResult.getBody().getCode() == 0) {

            //装框保存生产扎
            WoLots woLots = new WoLots();
            BeanUtils.copyProperties(order, woLots);
            woLots.setBoxCode(lcmBoxFill.getLcmBoxFillMaster().getBoxCode());
            LcmBoxFill lcmBoxFill1 = (LcmBoxFill) boxFillResult.getBody().getData();
            woLots.setFillBoxDocCode(lcmBoxFill1.getLcmBoxFillMaster().getDocCode());
            woLots.setWoOrder(order.getWoOrder());
            woLots.setCompanyId(machineInfo.getCompanyId());
            woLots.setCompanyCode(machineInfo.getCompanyCode());
            woLots.setCwocCode(order.getWorkCenterCode());
            woLots.setMachCode(order.getMachineCode());
            woLots.setDigit(lcmBoxFillDetail.getDigit());
            woLots.setEnterCode(principal.getName());
            woLots.setLotState(WoLotsStatus.USELOTS.getStatus());
            woLots.setCv4(order.getColorGroupCode());
            woLots.setCv4Name(order.getColorGroupName());
            woLots.setClientCode(order.getClientCode());
            woLots.setProjectCode(order.getProjectCode());
            woLots.setProjectName(order.getProjectName());
            woLots.setLength(new BigDecimal(order.getCv4()));
            woLots.setFormId(order.getFormId());
            woLots.setSystemId(requestParams.getSystemId());
            woLots.setCompanyId(requestParams.getCompanyId());
            woLots.setPeriodId(periodId);

            ResponseEntity<com.diligent.cloud.primary.data.model.Result> lotResult = lotsFeignService.insert(woLots);
            Preconditions.checkNotNull(lotResult.getBody(),"生成扎号失败");
            WoLots woLots1 = (WoLots) lotResult.getBody().getData();
            lcmBoxFill1.getLcmBoxFillDetail().setLotId(woLots1.getId());
            lcmBoxFill1.getLcmBoxFillDetail().setLotCode(woLots1.getLotCode());
            return new ObjectResult(lcmBoxFill1);
        } else {
            ObjectResult objectResult = new ObjectResult(null);
            objectResult.modifyCode(boxFillResult.getBody().getCode(), boxFillResult.getBody().getMsg());
            return objectResult;
        }
    }

    public static LinkedHashMap replaceFirstByMap(LinkedHashMap map) {
        Iterator iterator = map.entrySet().iterator();
        LinkedHashMap<String, Object> answer = new LinkedHashMap<>();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String) entry.getKey();
            answer.put(key.toLowerCase(), entry.getValue());
        }
        return answer;
    }
}
